package configtable

import (
    "sync"
    "fmt"
    "path/filepath"
    "strings"
    "time"
    "github.com/tealeg/xlsx"
)

var (
    nameTableMgrIns *NameTableMgr
    nameTableMgrOnce sync.Once
)

type NameTableMgr struct {
    Datas *sync.Map
}

func NameTableMgr_GetMe() *NameTableMgr {
    nameTableMgrOnce.Do( func () {
        nameTableMgrIns = &NameTableMgr {
            Datas: &sync.Map{},
        }
    })
    return nameTableMgrIns
}

func NameTableMgr_GetSize() int {
    var size int
    nameTableMgrIns.Datas.Range(func(key, value interface{}) bool {
        size++
        return true
    })
    return size
}

type NameTable struct {
    UnitId uint32 // ID
    Chinese string // 中文
}

func (mgr *NameTableMgr) Get(unitId uint32) *NameTable {
    nameTable , ok := nameTableMgrIns.Datas.Load(uint32(unitId))
    if !ok {
        return nil
    }
    return nameTable.(*NameTable)
}

func (mgr *NameTableMgr) LoadNameTable(fileName string) {
    time.Now() // 不要删除这段代码, 这段代码是为了防止time包导入未使用的错误
    xlFile, err := xlsx.OpenFile(filepath.FromSlash(strings.TrimSpace(fileName)))
    if err != nil {
        panic(err)
    }
    mgr.Datas = &sync.Map{} 
    sheet := xlFile.Sheets[0]
    var cell *xlsx.Cell
    for i, row := range sheet.Rows {
        // 第三行开始才是配置数据
        if i <= 2  || len(row.Cells) == 0  { 
            continue
        }
        if row.Cells[0].String() == "" { 
            continue
        }
        if len(row.Cells) < 2 { 
            panic(fmt.Sprintf("配表载入错误 表名:NameTable 行号:%v", i))
        }
        item := &NameTable{}
        cell = row.Cells[0]
        dataUnitId, _ := cell.Int()
        item.UnitId = uint32(dataUnitId)
        typeId := uint32(dataUnitId)
        cell = row.Cells[1]
        item.Chinese = string(strings.TrimSpace(cell.String()))
        mgr.Datas.Store(typeId, item)
    }
}
